package com.opensource.lzx.restartclient.netty;

import com.opensource.lzx.proto.RequestContext;
import com.opensource.lzx.proto.ServiceResponse;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: 739891618@qq.com
 * @Date: 2022-11-13 12:10:17
 * @ClassName: NettyClientTemplate
 * @Describe: this is a ...
 */
@Slf4j
public class NettyClientTemplate {
    private static final ConcurrentHashMap<String, Channel> CHANNEL_CACHE = new ConcurrentHashMap<>();

    private static final ConcurrentHashMap<String, CompletableFuture<ServiceResponse>> RESPONSE_CACHE = new ConcurrentHashMap<>();

    private static String clientSingleKey;

    public static void registerChannel(Channel channel) {
        clientSingleKey = channel.id().asLongText();
        log.info("Client register success and register key: {}", clientSingleKey);
        CHANNEL_CACHE.putIfAbsent(channel.id().asLongText(), channel);
    }

    public static String getChannelKey() {
        return clientSingleKey;
    }

    public static CompletableFuture<ServiceResponse> getFutureByRequestId(String requestId) {
        return RESPONSE_CACHE.remove(requestId);
    }

    public static<T> ServiceResponse sendMsg(RequestContext context, String channelKey) {
        Channel channel = CHANNEL_CACHE.get(channelKey);
        CompletableFuture<ServiceResponse> future = new CompletableFuture<>();
        RESPONSE_CACHE.putIfAbsent(context.getRequest().getRequestId(), future);
        channel.writeAndFlush(context);
        return future.join();
    }
}
